package com.thread.sync.sync07;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentMap;

//Master类: 负责给worker分配任务并接受任务结果
public class Master {
    //任务容器 ,适用于高并发队列
    private Queue<MyTask> tasks = new ConcurrentLinkedDeque<MyTask>();
    // worker集合
    private Map<String, Thread> workers = new HashMap<String, Thread>();
    //任务返回数据结果集合  并发容器
    private ConcurrentMap<String, Object> result = new ConcurrentHashMap<String, Object>();

    //构造器    worker数量,worker子类 ,指定worker数量
    public Master(int workerNum, Class<? extends Worker> workerClass) throws Exception {
        //可采用单worker多线程,也可采用多worker,多线程
        for (int i = 0; i < workerNum; i++) {
            //创建worker实例
            Worker worker = workerClass.newInstance();
            worker.setTasks(tasks);
            worker.setResult(result);
            this.workers.put(Integer.toString(i), new Thread(worker));
        }
    }

    //客户端提交任务给master
    public void submitTask(MyTask task) {
        this.tasks.add(task);
    }

    //执行方法
    public void executeTask() {
        //开启所有worker的线程,执行任务
        for (Map.Entry<String, Thread> me : workers.entrySet()) {
            me.getValue().start();
        }
    }

    //判断是否运行结束
    public boolean isFinished() {
        for (Map.Entry<String, Thread> me : workers.entrySet()) {
            //线程停止状态:Thread.State.TERMINATED
            if (me.getValue().getState() != Thread.State.TERMINATED) {
                return false;
            }
        }
        //即 所有worker线程都处于停止状态,才返回true
        return true;
    }

    //计算结果方法
    public int getResult() {
        //计算所有任务返回的结果之和
        int priceResult = 0;
        for (Map.Entry<String, Object> me : result.entrySet()) {
            priceResult += (Integer) me.getValue();
        }
        return priceResult;
    }
}
